import { useEffect, useState } from "react";
import { UserStatus } from "src/constant";
import { request } from "src/request";
import { clearObject } from "src/utils/transform";

export type User = {
  id: string;
  name: string;
  avatar: string;
  status: number;
  roles: string[];
}

export type UsersQuery = {
  status?: UserStatus
}

export function useUsers(query?: UsersQuery): [User[], () => Promise<void>] {
  const [users, setUsers] = useState([]);

  const fetchUsers = async () => {
    const response = await request.get('/user', clearObject(query));
    setUsers(response.data);
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  return [users, fetchUsers];
}

export function useUser(id?: string): [User | undefined, () => Promise<void>] {
  const [user, setUser] = useState<User>();

  const fetchUser = async () => {
    const response = await request.get(`/user/${id}`);
    setUser(response.data);
  };

  useEffect(() => {
    fetchUser();
  }, []);

  return [user, fetchUser];
}

